#!/usr/bin/env php
<?php
ini_set("memory_limit", '2048M');
ini_set("display_errors", "1");
ini_set("display_startup_errors", "1");

define("PID_FILE", "/var/run/php_connection_pool.pid"); //pid文件路径 不能修改
$config_file = "/etc/pool.ini"; //pool_server的配置文件

$usage = "Usage: pool_server {start|status|stop|restart}" . PHP_EOL;

$exit_code_ok = 0;
$exit_code_general = 1;
$exit_code_invoke = 126;

if (empty($argv[1])) {
    echo $usage;
    exit($exit_code_general);
}
$cmd = $argv[1];

if (is_readable($config_file) === false) {
    echo "Can NOT read config file, 请复制config.ini.example到{$config_file}路径下" . PHP_EOL;
    exit($exit_code_general);
}
if (parse_ini_file($config_file, true) === false) { //for stop && reload && test ini
    echo "Malformed configuration file {$config_file}, 请检查配置文件ini格式是否正确" . PHP_EOL;
    exit($exit_code_general);
}

$pid = false;
if ($cmd !== "start") {
    if (file_exists(PID_FILE) === false) {
        echo sprintf("The pid file %s does NOT exist, service is NOT running" . PHP_EOL, PID_FILE);
        exit($exit_code_invoke);
    } else {
        $pid = intval(file_get_contents(PID_FILE));
        if ($pid <= 0) {
            echo "Malformed pid file" . PHP_EOL;
            exit($exit_code_invoke);
        }
    }
}

$func_start = function ($config_file) {
    if (pool_server_create($config_file)) {
        return true;
    } else {
        echo "Start failed" . PHP_EOL;
        return false;
    }
};

$func_stop = function ($pid) {
    if (pool_server_shutdown($pid)) {
        if (unlink(PID_FILE) === false) {
            echo "Stop failed, deleting pid file failed" . PHP_EOL;
            return false;
        }
        return true;
    } else {
        echo "Stop failed" . PHP_EOL;
        return false;
    }
};

switch ($cmd) {
    case "start":
        exit($func_start($config_file) ? $exit_code_ok : $exit_code_general);
    case "status":
        pool_server_status($pid);
        exit($exit_code_ok);
    case "reload":
        echo "Tips: The reload can only modify 'pool_min','pool_max','recycle_num' and 'idel_time'" . PHP_EOL;
        if (pool_server_reload($pid)) {
            exit($exit_code_ok);
        } else {
            echo "Reload failed" . PHP_EOL;
            exit($exit_code_general);
        }
    case "stop":
        exit($func_stop($pid) ? $exit_code_ok : $exit_code_general);
    case "restart":
        exit($func_stop($pid) && sleep(1) && $func_start($config_file) ? $exit_code_ok : $exit_code_general);
    default:
        echo $usage;
        exit($exit_code_general);
}
